<template>
  <div class="body_">
    <!-- <div class="header">
      <div class="TitleForm">
        <el-form
          ref="SearchForm"
          :model="SearchForm"
          label-width="120px"
          inline
        >
          <el-form-item prop="name" label="歌曲名称">
            <el-input
              placeholder="请输入名称或编码"
              v-model="SearchForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item prop="state" label="设备状态">
            <el-input
              placeholder="选择设备状态"
              v-model="SearchForm.state"
            ></el-input>
          </el-form-item>

                   <el-form-item prop="name" label="设备编码">
                    <el-input
                       placeholder="请输入名称或编码"
                      v-model="SearchForm.name"
                      ></el-input>
                  </el-form-item>
        </el-form>
        <div class="queryBtn">
          <el-button @click="Select(true)" type="primary" icon="el-icon-search"
            >搜索</el-button
          >
          <el-button
            @click="resetSearchForm('SearchForm')"
            type="primary"
            icon="el-icon-refresh-left"
            >重置</el-button
          >
        </div>
      </div>
    </div> -->

    <div class="main">
      <div class="tableBtn">
        <el-button type="primary" icon="el-icon-plus" @click="SelectMusic()">新增</el-button>
      </div>
      <el-table :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
        :data="tableData" style="width: 100%">
        <el-table-column prop="id" type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="180">
        </el-table-column>
        <el-table-column prop="type" label="类型" width="180">
        </el-table-column>
        <el-table-column prop="rules" label="规则" width="180">
        </el-table-column>
        <el-table-column prop="playListName" label="播放列表" width="180">
        </el-table-column>
        <el-table-column prop="extensions" label="播放终端" width="180">
        </el-table-column>
        <el-table-column prop="time" label="创建时间" width="180">
        </el-table-column>
        <el-table-column prop="latLng" label="操作">
          <template slot-scope="scope">
            <!-- <span class="operter">编辑</span> -->
            <span class="operter" @click="delPlayList(scope.row)">删除 </span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <!-- <div class="block" style="margin-top: 15px">
        <el-pagination
          align="center"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
        >
        </el-pagination> -->
    </div>
    <el-dialog :title="DialogTitle" :visible.sync="AddDialogFormVisible" center width="30%" @close="CloseAddDialog">
      <el-form ref="AddForm">
        <el-form-item class="ipt_item" label="任务名称" label-width="120px" prop="name">
          <el-input v-model="name" class="ipt_item_Input" style="width: 330px;"></el-input>
        </el-form-item>
        <el-form-item class="ipt_item" label="播放源" label-width="120px" prop="name">
          <el-select size="medium" filterable :disabled="disabled" v-model="selectedPlay" placeholder="请选择"
            style="width: 330px;">
            <el-option v-for="item in selectOptions" :key="item.value" :label="item.key" :value="item.value"
              @click.native="changeSelect"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="ipt_item" label="播终端" label-width="120px" prop="name1">
          <el-select size="medium" multiple filterable :disabled="disabled1" v-model="selectedShebei"
            :loading="mulSelectLoading1" :collapse-tags="collapseTags1" placeholder="请选择" @remove-tag="removeTag1"
            style="width: 330px;">
            <el-option label="全部" value="全部" @click.native="selectAll1" v-if="selectOptions1.length"></el-option>
            <el-option v-for="item in selectOptions1" :key="item.value" :label="item.key" :value="item.value"
              @click.native="changeSelect1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="ipt_item" label="播放次数" label-width="120px" prop="name">
          <el-input v-model="count" class="ipt_item_Input" style="width: 330px;"  clearable @keyup.native="number" ></el-input>
        </el-form-item>
        <el-form-item>
           <div>任务一旦被添加将会被立即执行</div>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="AddDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

  </div>
  </div>
</template>

<script>
  import _ from 'lodash'
  import {
    IPPBXLogin,
    getTaskList,
    getPlayList,
    getPhoneList,
    delTask,
    palyMusic,
  } from "@/api/Audio";
  export default {
    name: 'MultipleSelect',
    name1: 'MultipleSelect',
    watch: {
      mulSelecteds1: {
        handler(newVal, oldVal) {
          this.selectedShebei = newVal
          if (
            !this.selectedShebei.includes('全部') &&
            this.selectedShebei.length &&
            this.selectedShebei.length === this.selectOptions1.length
          ) {
            this.selectedShebei.unshift('全部')
          }
          if (this.selectedShebei.includes('全部')) this.selectAll()
        },
        immediate: true,
      },
    },
    props: {
      // 选项
      selectOptions: {
        type: Array,
        default () {
          return []
        },
      },
      // 是否禁用
      disabled: {
        type: Boolean,
        default: false,
      },
      // 已选中选项
      mulSelecteds: {
        type: Array,
        default () {
          return []
        },
      },
      mulSelectLoading: {
        type: Boolean,
        default: false,
      },
      collapseTags: {
        type: Boolean,
        default: true,
      },
      compIndex: {
        type: [String, Number],
        default: null,
      },
      // 选项
      selectOptions1: {
        type: Array,
        default () {
          return []
        },
      },
      // 是否禁用
      disabled1: {
        type: Boolean,
        default: false,
      },
      // 已选中选项
      mulSelecteds1: {
        type: Array,
        default () {
          return []
        },
      },
      mulSelectLoading1: {
        type: Boolean,
        default: false,
      },
      collapseTags1: {
        type: Boolean,
        default: true,
      },
      compIndex1: {
        type: [String, Number],
        default: null,
      },
    },
    mounted() {
      this.login();
    },
    data() {
      return {
        authorization:"",
        tableData: [],
        selectedPlay: [],
        selectedIds: [],
        selectedSbIds: [],
        selectedShebei: [],
        playList: [],
        shebeiList: [],
        count:1,
        // 新增弹窗
        AddDialogFormVisible: false,
        DialogTitle: "创建播放任务",
        name: ""
      };
    },
    methods: {
      selectAll1() {
        const selectedArrLen = this.selectedShebei.length
        const selectOptionsLen = this.selectOptions1.length
        // 未全选(注意只有一个的条件判断)
        if (
          selectedArrLen < selectOptionsLen ||
          (selectedArrLen === 1 && selectedArrLen === selectOptionsLen)
        ) {
          this.selectedShebei = this.selectOptions1.map((el) => el.value)
          this.selectedShebei.unshift('全部')
        } else {
          // 已全选时，点击则取消全部
          this.selectedShebei = []
        }
        this.emitChangeSelect()
      },
      changeSelect1() {
        if (this.selectedShebei.includes('全部')) this.selectedShebei.shift('全部')
        if (this.selectedShebei.length == this.selectOptions1.length)
          this.selectedShebei.unshift('全部')
        this.emitChangeSelect1()
      },
      changeSelect() {
        const selectedList = _.cloneDeep(this.selectedShebei)
        this.$emit('changeSelect', selectedList, this.compIndex)
      },
      removeTag1(val) {
        if (val === '全部') {
          this.selectedShebei = []
        }
        this.emitChangeSelect1()
      },
      emitChangeSelect1() {
        const selectedList = _.cloneDeep(this.selectedShebei)
        if (selectedList.includes('全部')) selectedList.shift('全部')
        this.$emit('changeSelect', selectedList, this.compIndex)
      },
      CloseAddDialog() {
        this.$refs["AddForm"].resetFields();
        this.DialogTitle = "创建播放列表";
        this.isAdd = true;
        this.EditQuery = {};
      },
      // 登录
      async login() {
        let data = await IPPBXLogin();
        console.log(data);
        this.authorization=data.data;
        if(data.code==0){
           this. Select(true);
           this.SelectShebei();
        }

      },
      // 查询
      async Select(type) {
        if (type) {
          this.currentPage = 1;
        }
        let {
          data: res
        } = await getTaskList({
         authorization: this.authorization,
          page: this.currentPage,
          pageSize: this.pageSize,
        });
        console.log(res);
        this.tableData = [];
        //this.total = Number(res.count);
        res.forEach((e) => {
          let item = {
            id: e.uuid,
            name: e.name,
            type: e.type,
            playListName: e.playListName,
            extensions: e.extensions,
            time:e.created,
          };
          if (e.type === "now") {
            item.type = "即时";
          }
          this.tableData.push(item);
        });
      },
      // 删除该任务列表
      delPlayList(row) {
        this.$confirm("此操作将永久删除该播放任务列表, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            console.log(row);
            delTask({
              authorization: this.authorization,
              ids: "[" + row.id + "]"
            }).then((res) => {
              if (res.message) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.Select(true);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      async SelectMusic() {
        let {
          data: res
        } = await getPlayList({
          authorization: this.authorization,
          page: 1,
          pageSize: this.pageSize,
        });
        console.log(res);
        this.playList = [];
        this.selectOptions = [];
        this.playList = res.items;
        res.items.forEach((e) => {
          let item = {
            key: e.name,
            value: e.id
          };
          this.selectOptions.push(item);
        });
        this.AddDialogFormVisible = true;
      },
      async SelectShebei() {
        let {
          data: res
        } = await getPhoneList({
          authorization: this.authorization,
          page: 1,
          pageSize: this.pageSize,
        });
        console.log(res);
        this.shebeiList = [];
        this.selectOptions1 = [];
        this.shebeiList = res;
        res.forEach((e) => {
          let item = {
            key: e.name,
            value: e.name
          };
          this.selectOptions1.push(item);
        });
      },
      //添加播放任务
      submit() {
        if (this.name = "") {
          this.$message({
            type: "info",
            message: "请输入播放任务名称",
          });
        }
        if (this.selectedPlay.length == 0) {
          this.$message({
            type: "info",
            message: "请选择播放源",
          });
        }

        if (this.selectedShebei.length == 0) {
          this.$message({
            type: "info",
            message: "请选择播放终端",
          });
        }
        this.$confirm("创建的播放任务将会立即执行，是否继续添加", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            if (this.selectedShebei.includes('全部')) this.selectedShebei.shift('全部')
            palyMusic({
              cycleCount:this.count,
              name: this.name,
              authorization: this.authorization,
              playListID: this.playList[this.selectedPlay].id,
              extensions: "[" + this.selectedShebei.join(",") + "]"
            }).then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "添加成功!",
                });
                this.Select(true);
                this.AddDialogFormVisible = false;
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消添加",
            });
          });
      }
    },
  };
</script>

<style lang="scss" scoped>
  .body_ {
    overflow: hidden;
    padding-top: 0.2625rem;
    padding-left: 10px;
    padding-right: 10px;
    padding-bottom: 5px;
    display: flex;
    flex-direction: column;

    //height: 820px;
    .header {
      width: 100%;
      //height: 0.85rem /* 68/80 */;
      border-radius: 4px;
      background-color: rgb(255, 255, 255);
      box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
    }

    .main {
      margin-top: 0.3rem
        /* 24/80 */
      ;
      width: 100%;
      //height: 8.925rem /* 618/80 */;
      border-radius: 4px;
      background-color: rgb(255, 255, 255);
      box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
      flex: 1;
    }
  }

  .operter {
    color: rgba(59, 140, 255, 1) !important;
    cursor: pointer;
    margin-right: 4px;
  }
</style>
